home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C/C++ Users Group Library 1996 July
/
C-C++ Users Group Library July 1996.iso
/
listings
/
v_07_06
/
v7n6035a.txt
< prev
next >
Wrap
Text File
|
1989-07-23
|
1KB
|
71 lines
// VEC.CXX: An integer vector to illustrate the
// need for the copy-initializer
#include <stdio.h>
class vec { // an integer vector
int size;
int * vp;
public:
vec(int i = 0, int j = 0);
vec(vec & rv);
~vec() { delete vp; }
vec operator=(vec & rv);
void print(char * msg = "");
int & operator[](int x);
int length() { return size; }
};
vec::vec(int i, int j) {
vp = new int[size = i];
for (int x = 0; x < size; x++)
vp[x] = j;
}
vec::vec(vec & rv) {
vp = new int[size = rv.size];
for (int x = 0; x < size; x++)
vp[x] = rv.vp[x];
}
vec vec::operator=(vec & rv) {
delete vp; // release old memory
vp = new int[size = rv.size];
for (int x = 0; x < size; x++)
vp[x] = rv.vp[x];
return *this; // return a copy of this object
}
void vec::print(char * msg) {
printf("%s",msg);
for(int x = 0; x < size; x++)
printf("%d ",vp[x]);
printf("\n");
}
int & vec::operator[](int x) {
if (x < size)
return vp[x];
else {
puts("vec index out of range");
exit(1);
}
}
// pass in by value, return by value:
vec func1(vec value) {
if (value.length() >= 1)
value[0] = 0;
return value;
}
main() {
vec A(4,3);
vec B;
A.print("A: ");
B.print("B: ");
B = func1(A);
A.print("A after func1: ");
B.print("B after func1: ");
}